<?php

namespace App\Services\ApplyGoldCoinWithdrawMyBank;

use App\Models\User;
use App\Models\Withdraw;
use Brick\Math\BigDecimal;
use Illuminate\Support\Facades\DB;

class ApplyGoldCoinWithdrawMyBank
{
	/**
	 * @var User
	 */
	protected $user;
	
	
	protected $chargeType;
	
	/**
	 * @var BigDecimal
	 */
	protected $chargeFee;
	
	/**
	 * @var BigDecimal
	 */
	protected $targetAmount;
	
	/**
	 * @var BigDecimal
	 */
	protected $actualAmount;
	
	protected $payCode = null;
	
	
	public function __construct(User $user, $coins)
	{

		$this->user = $user;
		$this->chargeType = Withdraw::chargeType();

		$this->chargeFee = Withdraw::willChargeFeeByXzb($coins);
		$this->targetAmount = big_decimal($coins);
		$this->actualAmount = Withdraw::willActuallyGetCoinsByXzb($coins);
		
	}
	
	protected function isWithdrawOn()
	{
		return Withdraw::isWithdrawOn();
	}
	
	protected function allowedLowestAmount()
	{
		return Withdraw::allowedLowestAmount();
	}
	
	protected function isLowestAmountMatched()
	{
		return Withdraw::isLowestAmountMatched($this->targetAmount);
	}
	
	protected function allowedHighestAmount()
	{
		return Withdraw::allowedHighestAmount();
	}
	
	protected function isHighestAmountMatched()
	{
		return Withdraw::isHighestAmountMatched($this->targetAmount);
	}
	
	protected function isGoldCoinsEnough()
	{
		return Withdraw::isCoinsEnoughToDeduct($this->user, $this->targetAmount);
	}


	
	
	protected function create()
	{
		return $this->user->withdraws()->create([
			'target_amount' => $this->targetAmount,
			'charge_type' => $this->chargeType,
			'charge_amount' => $this->chargeFee,
			'actual_amount' => $this->actualAmount,
			'method' => 'mybank',
			'channel' => 'local'
		]);
	}
	
	public function apply()
	{
		if ($this->user->refresh()->balances <= 0) return;
		

		DB::transaction(function () {
			$withdraw = $this->create();
			$data = ['withdraw_id' => $withdraw->id];
			account_balances($this->user)->minusWithdrawPrincipal($this->actualAmount, $data);
			account_balances($this->user)->minusWithdrawCharge($this->chargeFee, $data);
			
		});
	}
}
